import java.util.*;

/**
 * @program: 力扣刷题
 * @description
 * @author: LiChong
 * @create: 2021-05-10 14:17
 **/
public class Code03 {
    /**
     * 题目：无重复字符的最长子串
     * 描述：给定一个字符串，请你找出其中不含有重复字符的 最长子串 的长度。
     * eg:输入: s = "abcabcbb"
     * 输出: 3
     * 解释: 因为无重复字符的最长子串是 "abc"，所以其长度为 3。
     *
     * @param
     * @return
     */
    public static void main(String[] args) {
        String s = "aab";
        int i = lengthOfLongestSubstring2(s);
        System.out.println(i);


    }

    // 解法1：暴力遍历
    public static int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) return 0;
        if (s.length() == 1) return 1;
        ArrayList<String> temp = new ArrayList<>();
        int maxSize = 0;
        boolean breakLoop = false;
        for (int i = 0; i < s.length(); i++) {
            temp.add(s.substring(i, i + 1));
            for (int j = i + 1; j < s.length(); j++) {
                String cur = s.substring(j, j + 1);
                boolean b = ifContain(temp, cur);
                if (b) {
                    if (temp.size() > maxSize) {
                        maxSize = temp.size();
                    }
                    temp.clear();
                    breakLoop = true;
                    break;
                } else {
                    temp.add(cur);
                    if (temp.size() > maxSize) {
                        maxSize = temp.size();
                    }
                }
            }
            if (breakLoop) {
                breakLoop = false;

            } else {
                if (temp.size() >= maxSize) {
                    return maxSize;
                } else {
                    temp.clear();
                }
            }

        }
        return maxSize;

    }

    public static boolean ifContain(List<String> arr, String s) {
        for (String c : arr) {
            if (s.equals(c)) {
                return true;
            }
        }
        return false;
    }
    // 解法2
    public static int lengthOfLongestSubstring2(String s){
        if (s==null||s.length()==0) return 0;
        if (s.length()==1) return 1;
        HashMap<Character, Integer> map = new HashMap<>();
        int restartIndex = 0 ;
        int res = 0,start=0,end=0 ;
        for (int i = 0; i <s.length(); i++) {
            Character curChar = s.charAt(i);
            if (map.containsKey(curChar)){
                int temp = end - start+1;
                if (temp>res){
                    res = temp;
                }
                if (map.get(curChar)>restartIndex){
                    restartIndex = map.get(curChar)+1;
                }
                start = restartIndex+1;
            }
            end = i;
            map.put(curChar,i);
        }
         return Math.max(res,end-start+1);
    }

}
